package com.ruoyi.whzj.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.HttpClientConnectionManager;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.OkHttpUtil;
import com.ruoyi.whzj.domain.WhTasksetting;
import com.ruoyi.whzj.domain.WhUser;
import com.ruoyi.whzj.service.IWhTasksettingService;
import com.ruoyi.whzj.service.IWhUserService;
import org.apache.http.client.methods.HttpPost;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.whzj.domain.WhTask;
import com.ruoyi.whzj.service.IWhTaskService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 任务Controller
 * 
 * @author ruoyi
 * @date 2020-10-16
 */
@Controller
@Component("whTaskController")
@RequestMapping("/whzj/task")
public class WhTaskController extends BaseController
{
    private String prefix = "whzj/task";

    @Autowired
    private IWhTaskService whTaskService;

    @Autowired
    private IWhUserService whUserService;

    @Autowired
    private IWhTasksettingService whTasksettingService;

    @RequiresPermissions("whzj:task:view")
    @GetMapping(value = "/task")
    public String task()
    {
        return prefix + "/task";
    }

    @RequiresPermissions("whzj:task:viewStar")
    @GetMapping(value = "/starTask")
    public String starTask()
    {
        return prefix + "/starTask";
    }
    @RequiresPermissions("whzj:task:viewComment")
    @GetMapping(value = "/commentTask")
    public String commentTask()
    {
        return prefix + "/commentTask";
    }
    @RequiresPermissions("whzj:task:viewAttention")
    @GetMapping(value = "/attentionTask")
    public String attentionTask()
    {
        return prefix + "/attentionTask";
    }
    @RequiresPermissions("whzj:task:viewPlay")
    @GetMapping(value = "/playTask")
    public String playTask()
    {
        return prefix + "/playTask";
    }

    @RequiresPermissions("whzj:task:view")
    @GetMapping(value = "/checkTask")
    public String checkTask()
    {
        return prefix + "/checkTask";
    }

    /**
     * 查询任务列表
     */
    @RequiresPermissions("whzj:task:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WhTask whTask)
    {
        startPage();
        List<WhTask> list = whTaskService.selectWhTaskList(whTask);
        for(WhTask temp :list){
            if("关注".equals(temp.getType())){
                temp.setWorkId("http://kpfshanghai.m.chenzhongtech.com/fw/user/"+temp.getWorkId());
            }else{
                temp.setWorkId("http://kphbeijing.m.chenzhongtech.com/fw/photo/"+temp.getWorkId());
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询任务列表
     */
    @RequiresPermissions("whzj:task:list")
    @PostMapping("/checkList")
    @ResponseBody
    public TableDataInfo checkList(WhTask whTask)
    {
        startPage();
        whTask.setType("登录验证");
        List<WhTask> list = whTaskService.selectWhTaskList(whTask);
        return getDataTable(list);
    }

    /**
     * 导出任务列表
     */
    @RequiresPermissions("whzj:task:export")
    @Log(title = "任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WhTask whTask)
    {
        List<WhTask> list = whTaskService.selectWhTaskList(whTask);
        ExcelUtil<WhTask> util = new ExcelUtil<WhTask>(WhTask.class);
        return util.exportExcel(list, "task");
    }

    /**
     * 新增任务
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存任务
     */
    @RequiresPermissions("whzj:task:add")
    @Log(title = "任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WhTask whTask)
    {
        whTask.setUserId("1");
        whTask.setIsTop("0");
        whTask.setSpeed("0");
        whTask.setStatus("进行中");
        whTask.setId(IdWorker.getId());
        int num = whTaskService.insertWhTask(whTask);
        if(num >0){
            //修改用户验证任务状态
            whUserService.updateWhUserCheckFlag();
        }
        return toAjax(num);
    }

    /**
     * 修改任务
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        WhTask whTask = whTaskService.selectWhTaskById(id);
        mmap.put("whTask", whTask);
        return prefix + "/edit";
    }

    /**
     * 修改保存任务
     */
    @RequiresPermissions("whzj:task:edit")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WhTask whTask)
    {
        int num = whTaskService.updateWhTask(whTask);
        if("播放".equals(whTask.getType())){
            return toAjax(num);
        }else{
            if(num >0){
                //修改用户验证任务状态
                whUserService.updateWhUserCheckFlag();
            }
            return toAjax(num);
        }
    }

    /**
     * 删除任务
     */
    @RequiresPermissions("whzj:task:remove")
    @Log(title = "任务", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        WhTask whTask = new WhTask();
        whTask.setType("登录验证");
        int size = whTaskService.selectWhTaskList(whTask).size();
        if(size >1){
            int num = whTaskService.deleteWhTaskByIds(ids);
            if(num >0){
                //修改用户验证任务状态
                whUserService.updateWhUserCheckFlag();
            }
            return toAjax(num);
        }else{
            return error("验证任务最少要保留一条");
        }
    }

    /**
     * 修改任务
     */
    @GetMapping("/updateWorkId/{id}")
    public String updateWorkId(@PathVariable("id") String id, ModelMap mmap)
    {
        WhTask whTask = whTaskService.selectWhTaskById(id);
        mmap.put("whTask", whTask);
        return prefix + "/updateWorkId";
    }

    /**
     * 修改任务
     */
    @PostMapping( "/checkTaskInfo")
    @ResponseBody
    public AjaxResult checkTaskInfo()
    {
        Boolean flag=false;
        WhTask whTask = new WhTask();
        whTask.setType("登录验证");
        List<WhTask> whTaskList = whTaskService.selectWhTaskList(whTask);
        List<WhUser> whUserList = whUserService.selectWhUserList(new WhUser());
        for(WhUser temp :whUserList){
            if("1".equals(temp.getCheckFlag())){
                flag =true;
                break;
            }
        }
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",flag);
    }

    /**
     * 执行播放任务
     */
    @PostMapping( "/doPlayTask")
    @ResponseBody
    public AjaxResult doPlayTask(String id)
    {
        WhTask whTask = whTaskService.selectWhTaskById(id);
        //获取任务配置参数
        WhTasksetting whTasksetting = whTasksettingService.selectWhTasksettingById("1");
        String taskUrl = whTasksetting.getPlayApi();
        String taskParam = whTasksetting.getPlayPara();
        //执行下单
        Map<String,String> paramMap = new HashMap<>();
        String[] parseStr = taskParam.split("&");
        for(int i=0;i<parseStr.length;i++){
            String[] temp = parseStr[i].split("=");
                if("ksid".equals(temp[0])){
                    paramMap.put(temp[0],whTask.getUserId());
                }else if("zpid".equals(temp[0])){
                    paramMap.put(temp[0],whTask.getWorkId());
                }else if("need_num_0".equals(temp[0])){
                    paramMap.put(temp[0],whTask.getAllNum().toString());
                }else{
                    paramMap.put(temp[0],temp[1]);
                }
        }
        String resultStr = OkHttpUtil.postFormParams(taskUrl,paramMap);
        System.out.println(resultStr);
        if(resultStr.indexOf("order_id")>0){
            String[] returnStr = resultStr.split(",");
            for(int i=0;i<returnStr.length;i++){
                String[] tempin = returnStr[i].split(":");
                if("\"order_id\"".equals(tempin[0])){
                    System.out.println("order_id++++++++"+tempin[1]);
                    whTask.setTaskOrder(tempin[1].replace("\"",""));
                    whTaskService.updateWhTask(whTask);
                }
            }
        }
        return new AjaxResult(AjaxResult.Type.SUCCESS,"200",resultStr);
    }

    public void updatePlayTask(){
        WhTask whTask = new WhTask();
        whTask.setType("播放");
        whTask.setStatus("进行中");
        List<WhTask> whTaskList = whTaskService.selectWhTaskList(whTask);
        for(WhTask temp :whTaskList){
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(sd.format(temp.getUpdateTime()));
            System.out.println(sd.format(new Date()));
            System.out.println(dateDiff(sd.format(temp.getUpdateTime()),sd.format(new Date()),"yyyy-MM-dd HH:mm:ss","h"));
            if(dateDiff(sd.format(temp.getUpdateTime()),sd.format(new Date()),"yyyy-MM-dd HH:mm:ss","h")>24){
                temp.setStatus("已完成");
                temp.setNum(temp.getAllNum());
                whTaskService.updateWhTask(temp);
            }
        }
    }

    /**
     *
     * @param startTime
     * @param endTime
     * @param format
     * @param str  d-天,h-小时,m-秒 表示返回相差的时间单位
     * @return
     */
    public static Long dateDiff(String startTime, String endTime, String format, String str) {
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        String result = "0";
        // 获得两个时间的毫秒时间差异
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            day = diff / nd;// 计算差多少天
            hour = diff % nd / nh + day * 24;// 计算差多少小时
            min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
            sec = diff % nd % nh % nm / ns;// 计算差多少秒
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("时间相差：" + day + "天" + (hour - day * 24) + "小时"
                + (min - day * 24 * 60) + "分钟" + sec + "秒。");

        if ("d".equalsIgnoreCase(str)){
            return day;
        } else if ("h".equalsIgnoreCase(str)) {
            return hour;
        } else if ("m".equalsIgnoreCase(str)){
            return min;
        } else {
            return 0L;
        }

    }

}
